/**
 * 封装Ajax</br> 参数说明：</br> opts: {'可选参数'}</br> type:
 * 请求方式:GET/POST,默认值:'GET';</br> url: 发送请求的地址, 默认值: 当前页地址;</br> data:
 * 请求参数;</br> data: string,json;</br> async: 是否异步:true/false,默认值:true;</br>
 * cache: 是否缓存：true/false,默认值:true;</br> contentType:
 * HTTP头信息，默认值：'application/x-www-form-urlencoded';</br> success:
 * 请求成功后的回调函数;</br> error: 请求失败后的回调函数;</br>
 */
;
//注册命名空间
var NameSpace = {
    register: function () {
        var arg = arguments[0];
        var arr = arg.split('.');
        var str = '';
        for (var i = 0; i < arr.length; i++) {
            str = i == 0 ? arr[i] : (str + '.' + arr[i]);
            var sval = "   if(typeof " + str + "=='undefined' ) { " + str + "= new Object(); } ";
            eval(sval) ;
        };
    }
};
//注册应用命名空间
NameSpace.register("cmedit");
cmedit.util = (function ($, window, document) {
    return {
        ajaxRequest: function (opts) {
            // 一.设置默认参数
            var defaults = {
                url: '',
                type: '',
                data: '',
                cache: true,
                async: false,
                dataType: 'json',
//                contentType: "application/json;charset=UTF-8",
                success: function () {
                },
                error: function () {
                }
            };

            // 二.用户参数覆盖默认参数
            for (var key in opts) {
                defaults[key] = opts[key];
            }
            var userInfo={
            		tenantId : "dayang.com",
            		userId : "0003",
            		token : "a",
            		userName : "dayang"
            		/*userName : "encodeURIComponent('dayang')"*/
            }
            window.sessionStorage.setItem("userInfo",JSON.stringify(userInfo));
            var userInfoItem = window.sessionStorage.getItem("userInfo");
            var userInfo = null;
            var userId = "";
            var tenantId = "";
            var userName = "";
            var token = "";
            if (userInfoItem != undefined && userInfoItem != null && userInfoItem != "" && userInfoItem != "undefined" && userInfoItem != "null") {
                userInfo = JSON.parse(userInfoItem);
                userId = userInfo.userId;
                tenantId = userInfo.tenantId;
                token = userInfo.token;
                userName=userInfo.userName;
            } else {
            	cmedit.global.forceLogout("用户信息为空！");
            }
            
            var tenantId = window.localStorage.getItem("tenantId");
            var userId = window.sessionStorage.getItem("userId");
            var token = window.sessionStorage.getItem("token");
            var userName = window.sessionStorage.getItem("userName");
            userName = encodeURIComponent(userName);
            
//            cmedit.ManuscriptSystem.updatePortalStorageExpireTime();
            // 三.开始组装ajax
            $.ajax({
                url: defaults.url,
                type: defaults.type,
                data: defaults.data,
                async: defaults.async,
                cache: defaults.cache,
                dataType: defaults.dataType,
                contentType: defaults.contentType,
                beforeSend: function (XHR) {
                    XHR.setRequestHeader("userId", userId);
                    XHR.setRequestHeader("tenantId", tenantId);
                    XHR.setRequestHeader("token", token);
                    XHR.setRequestHeader("userName", userName);
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    console.log("错误信息" + errorThrown.toString());
                },
                success: defaults.success
            });
        },
        isNotEmpty: function(obj){
            var isflag = false;
            if(obj!=null&&obj!=''&&obj!=undefined&&obj!='undefined'){
                isflag = true;
            }
            return isflag;
        },
        //弹出框
        alert:function(callback,dialogBody){
//			var config = {
//				dialogBody:dialogBody,
//				title:"温馨提示",
//				noClose:false
//			};
//			Global.dialog(config);
            bootbox.setDefaults("locale","zh_CN");
//            bootbox.alert(dialogBody);
            bootbox.confirm({   
                message: dialogBody,  
                callback: callback,  
                title: "",  
            });  
        },
        /**
         * 对日期进行格式化，
         * @param date 要格式化的日期
         * @param format 进行格式化的模式字符串
         *     支持的模式字母有：
         *     y:年,
         *     M:年中的月份(1-12),
         *     d:月份中的天(1-31),
         *     h:小时(0-23),
         *     m:分(0-59),
         *     s:秒(0-59),
         *     S:毫秒(0-999),
         *     q:季度(1-4)
         * @return String
         */
        dateFormat : function (date, format){

            date = new Date(date);
            var map = {
                "M": date.getMonth() + 1, //月份
                "d": date.getDate(), //日
                "h": date.getHours(), //小时
                "m": date.getMinutes(), //分
                "s": date.getSeconds(), //秒
                "q": Math.floor((date.getMonth() + 3) / 3), //季度
                "S": date.getMilliseconds() //毫秒
            };

            format = format.replace(/([yMdhmsqS])+/g, function(all, t){
                var v = map[t];
                if (v !== undefined) {
                    if (all.length > 1) {
                        v = '0' + v;
                        v = v.substr(v.length - 2);
                    }
                    return v;
                }
                else if (t === 'y') {
                    return (date.getFullYear() + '').substr(4 - all.length);
                }
                return all;
            });
            return format;
        },
        //字节转换成其它类型的单位
        bytesToSize: function (bytes) {
            if (bytes === 0) return '0 B';
            var k = 1024;
            var sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
            var i = Math.floor(Math.log(bytes) / Math.log(k));
            return (bytes / Math.pow(k, i)).toFixed(2) + ' ' + sizes[i];
        },
        //从url中根据名称获取参数
        getParameterFromUrl: function (parameterName) {
            var reg = new RegExp("(^|&)" + parameterName + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r != null)return decodeURIComponent(r[2]);;
            return null;
        },
        /**
		 * 动态加载js文件
		 */
		loadScript : function(url) {
			var script = document.createElement("script");
			script.type = "text/javascript";
			script.src = url;
			document.body.appendChild(script);
		},
		/**
		 * 动态加载css文件
		 */
		loadStyles : function(url) {
			var link = document.createElement("link");
			link.type = "text/css";
			link.rel = "stylesheet";
			link.href = url;
			document.getElementsByTagName("head")[0].appendChild(link);
		},
		/**
		 * 生成随机正整数(1-100)
		 */
		randomNum : function() {
			//x上限，y下限     
		    var x = 100;     
		    var y = 1;     
		    var rand = parseInt(Math.random() * (x - y + 1) + y);     

			return rand;
		},
        /**
         * 根据稿件类型，获取稿件的前端地址
         * @param maintype 稿件类型
         * @returns
         */
        getAppPathByType : function(maintype){
        	var app;
        	if(maintype == '0'){
        		app = cmedit.util.getAppByCode("PID_Fast_cmedit_cms");
        	}
        	if(maintype == '1'){
        		app = cmedit.util.getAppByCode("PID_Fast_cmedit_wechat");
        	}
        	if(maintype == '2'){
        		app = cmedit.util.getAppByCode("PID_Fast_cmedit_weibo");
        	}
        	if(maintype == '3'){
        		app = cmedit.util.getAppByCode("PID_Fast_cmedit_tv");
        	}
        	if(maintype == '4'){
        		app = cmedit.util.getAppByCode("PID_Fast_cmedit_release");
        	}
        	return app.appUrl;
        },
        /**
         * 根据应用code从应用信息
         * 
         * @param appCode 应用代码
         * @returns
         */
        getAppByCode: function (appCode) {
            var app = "";
            $.ajax({
                type: 'POST',
                async: false,
				url: cmedit.global.portalPath + "AppController/getAppList",
				data: {
					appCode : appCode
				},
                success: function (data) {
                    if (data.status == true || data.status == "true") {
                    	app = data.data[0];
                    } else {
                        cmedit.util.alertMsgNoCancel(data.msg);
                    }
                }
            });
            return app;
        },
        /**
         * 无取消按钮的提示框
         * @param content  提示内容
         */
        alertMsgNoCancel: function (content) {
            art.dialog({
                content: content,
                height: 60,
                width: 300,
                lock: true,
                focus: true,
                zIndex: 99999999
            }, function () {
            });
        },
        /**
         * 定时关闭消息
         * @param content  提示内容
         */
        alertTimeMsgNoCancel: function (content) {
           /* art.dialog({
            	time: 1,
                content: content,
                height: 60,
                width: 300,
                lock: true,
                focus: true,
                zIndex: 99999999
            });*/
        	$("body").dyArt({
        		content:content,
        		isHide:false,
        		Time:2000
        	})
        },
        /**
         * 提示框
         * callback 回调函数
         * key 提示描述
         */
        alertMsg: function (callback, content) {
            art.dialog({content: content, height: 60, width: 300, lock: true, focus: true}, function () {
                // 先保存稿件信息
                callback(true);
            }, function () {
            });
        },
        autoResizeImage: function (maxWidth, maxHeight, objImg) {
            var img = new Image();
            img.src = objImg.src;
            var hRatio;
            var wRatio;
            var Ratio = 1;
            var w = img.width;
            var h = img.height;
            wRatio = maxWidth / w;
            hRatio = maxHeight / h;
            if (maxWidth == 0 && maxHeight == 0) {
                Ratio = 1;
            } else if (maxWidth == 0) {//
                if (hRatio < 1) Ratio = hRatio;
            } else if (maxHeight == 0) {
                if (wRatio < 1) Ratio = wRatio;
            } else if (wRatio < 1 || hRatio < 1) {
                Ratio = (wRatio <= hRatio ? wRatio : hRatio);
            }
            if (Ratio < 1) {
                w = w * Ratio;
                h = h * Ratio;
            }
            objImg.height = h;
            objImg.width = w;
        },
        getContextPath: function (pathName) {
            var index = pathName.substr(1).indexOf("/");
            var result = pathName.substr(0, index + 1);
            return result;
        },
        //显示数据加载中遮罩
        showLoading:function(select) {
            $(select).showLoading();
        },
        //隐藏数据加载中遮罩
        hideLoading:function(select) {
            $(select).hideLoading();
        },
        //弹出页面
        tipsWindowsDialog:function(title,content,width,height,drag,time,showbg,cssName){
            tipsWindown(title,content,width,height,drag,time,showbg,cssName)
        },
        /**
         * 将驼峰式命名的字符串转换为下划线大写方式。如果转换前的驼峰式命名的字符串为空，则返回空字符串。</br>
         * 例如：HelloWorld->HELLO_WORLD
         * @param name 转换前的驼峰式命名的字符串
         * @return 转换后下划线大写方式命名的字符串
         */
        underScoreName : function(name) {
        	if(cmedit.util.isNotEmpty(name)){
        		var result = name.replace(/([A-Z])/g,"_$1").toLowerCase()
                return result.toString();
        	}else{
        		return "";
        	}
            
        },

        /**
         * 将下划线大写方式命名的字符串转换为驼峰式。如果转换前的下划线大写方式命名的字符串为空，则返回空字符串。</br>
         * 例如：HELLO_WORLD->HelloWorld
         * @param name 转换前的下划线大写方式命名的字符串
         * @return 转换后的驼峰式命名的字符串
         */
        camelName : function(name) {
        	if(cmedit.util.isNotEmpty(name)){
//        		var re=/_(\w)/g;
        		var result = name.replace(/_(\w)/g, function(all, letter){
      	          return letter.toUpperCase();
      	        })
      	        return result.toString();
        	}else{
        		return "";
        	}
        	
        }
    };
})(jQuery, window, document);



